#include "Dialog.h"
#include "ui_Dialog.h"

#include <QDebug>

Dialog::Dialog(QWidget* parent) : QDialog(parent), ui(new Ui::Dialog) {
    ui->setupUi(this);

    // 窗口大小设置为600*500
    resize(600, 500);
    // 画布大小为200*200，背景为白色
    pixmap = QPixmap(200, 200);
    pixmap.fill(Qt::white);

    // 设置按钮显示文本
    button->setText(tr("zoomIn"));
    // 设置按钮放置位置
    button->move(500, 450);
    // 对按钮的单击事件和其槽函数进行关联
    connect(button, &QPushButton::clicked, this, &Dialog::zoomIn);
}

Dialog::~Dialog() {
    delete ui;
}

void Dialog::paintEvent(QPaintEvent*) {
    //    qDebug() << "Last Point: " << lastPoint << ", End Point: " <<
    //    endPoint; if (scale != 1) {
    //        // 如果进行放大操作
    //        // 临时画布，大小变化了scale倍
    //        QPixmap  copyPix(pixmap.size() * scale);
    //        QPainter copyPixPainter(&copyPix);
    //        copyPixPainter.scale(scale, scale);
    //        // 将以前画布上的内容复制到现在的画布上
    //        copyPixPainter.drawPixmap(0, 0, pixmap);
    //        // 将放大后的内容再复制回原来的画布上
    //        pixmap = copyPix;
    //        // 将scale重新置为1
    //        scale = 1;
    //    }
    //    QPainter pixPainter(&pixmap);
    //    pixPainter.scale(scale, scale);
    //    pixPainter.drawLine(lastPoint / scale, endPoint / scale);
    //    lastPoint = endPoint;
    //    QPainter painter(this);
    //    painter.drawPixmap(0, 0, pixmap);

    int x = lastPoint.x();
    int y = lastPoint.y();
    int w = endPoint.x() - x;
    int h = endPoint.y() - y;

    QPainter painter(this);
    if (isDrawing) {
        // 如果正在绘图，就在辅助画布上绘制
        // 将以前pixmap中的内容复制到tmpPixmap中，保证以前的内容不消失
        tmpPixmap = pixmap;
        QPainter pixPainter(&tmpPixmap);
        pixPainter.drawRect(x, y, w, h);
        painter.drawPixmap(0, 0, tmpPixmap);
    } else {
        QPainter pixPainter(&pixmap);
        pixPainter.drawRect(x, y, w, h);
        painter.drawPixmap(0, 0, pixmap);
    }
}

void Dialog::mousePressEvent(QMouseEvent* event) {
    // 鼠标左键按下
    if (event->button() == Qt::LeftButton) {
        lastPoint = event->pos();
        isDrawing = true;
    }
}

void Dialog::mouseMoveEvent(QMouseEvent* event) {
    // 鼠标左键按下的同时移动鼠标
    if (event->buttons() & Qt::LeftButton) {
        endPoint = event->pos();
        update(); // 进行绘制
    }
}

void Dialog::mouseReleaseEvent(QMouseEvent* event) {
    // 鼠标左键释放
    if (event->button() == Qt::LeftButton) {
        endPoint  = event->pos();
        isDrawing = false;
        update();
    }
}

void Dialog::zoomIn() {
    scale *= 2;
    update();
}
